package com.amado.course50java8;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Java810Stream {
    static List<Drug> drugList = new ArrayList();
    static{
        drugList.add(new Drug("code1", 1, 10, 1));
        drugList.add(new Drug("code2", 3, 10, 1));
        drugList.add(new Drug("code3", 4, 10, 2));
        drugList.add(new Drug("code4", 5, 30, 1));
        drugList.add(new Drug("code4", 6, 30, 1));
        drugList.add(new Drug("code4",  7, 30, 1));
        drugList.add(new Drug("code3", 8, 14, 2));
        drugList.add(new Drug("code4", 9, 10, 3));
    }
    public static void main(String[] args) {
        new Java810Stream().toListMap();
        new Java810Stream().toMap();
    }

    /**
     * List<E>转换为Map<String,List<E>></>
     */
    public void toListMap() {
        //过滤e.getType==1的数据，再根据e.getCode()分组
        Map<String, List<Drug>> filtered = drugList.stream().filter(e -> e.getType() == 1).collect(Collectors.groupingBy(Drug::getCode));
        filtered.entrySet().forEach(System.out::println);
    }
    /**
     * List<E>转换为Map<String,E></>
     */
    public void toMap() {
        System.out.println("------------------");
        //过滤e.getType==1的数据，再根据e.getCode()分组
        /**
         * List -> Map
         * 需要注意的是：
         * toMap 如果集合对象有重复的key，会报错Duplicate key ....
         *  apple1,apple12的id都为1。
         *  可以用 (k1,k2)->k1 来设置，如果有重复的key,则保留key1,舍弃key2
         */
        Map<String, Drug> filtered = drugList.stream().filter(e -> e.getType() == 1).collect(Collectors.toMap(Drug::getCode,e->e,(e1,e2)->e1));
        filtered.entrySet().forEach(System.out::println);
    }

    static class Drug {
        private String code;
        private int count;
        private int price;
        private int type;

        public Drug(String code, int count, int price, int type) {
            super();
            this.code = code;
            this.count = count;
            this.price = price;
            this.type = type;
        }

        public int getType() {
            return type;
        }

        public void setType(int type) {
            this.type = type;
        }

        public String getCode() {
            return code;
        }

        public void setCode(String code) {
            this.code = code;
        }

        public int getCount() {
            return count;
        }

        public void setCount(int count) {
            this.count = count;
        }

        public int getPrice() {
            return price;
        }

        public void setPrice(int price) {
            this.price = price;
        }

        @Override
        public String toString() {
            return "Drug [code=" + code + ", count=" + count + ", price=" + price + ", type=" + type + "]";
        }

    }

}
